 package com.ibm.broker.as400plugin;


import com.ibm.as400.access.AS400;
import com.ibm.as400.access.AS400ConnectionPool;
import com.ibm.as400.access.DataQueue;
import com.ibm.as400.access.QSYSObjectPathName;


import com.ibm.broker.plugin.*;

public class as400oNode extends MbNode implements MbNodeInterface {

	int creado = 0;
	int contador = 0;
	
	private String host;
	private String user;
	private String password;
	private String libDTQ;
	private String nameDTQ;
	private int logLevel;
	private int numConn;
	
	private AS400ConnectionPool as400Pool;
	private QSYSObjectPathName pathIn = null;
	
	
	
	private LogTraceData logdt = null;
	
	
	// Constructor 
	public as400oNode() throws MbException {
		// create terminals here
		createInputTerminal("in");		
		createOutputTerminal("out");
		//createOutputTerminal("failure");
		
		logdt = new LogTraceData("as400o.log");//LogTraceData.getInstance();
		
	}
	
	
	// ---------------------------------	
	// WMQI Node name
	public static String getNodeName() {
		return "as400oNode";
	}
	// ---------------------------------	
	// FTP command port accessors

	// ---------------------------------	
	// WMQI input node execution loop
	public void evaluate(MbMessageAssembly assembly, MbInputTerminal inTerminal) throws MbException {
       
		AS400 as400 = null;
		DataQueue kdqIn = null;
		
		logdt.setlogDataLevel(this.getLogLevel());
		
		logdt.logData_Debug("Ejecucion del evaluate");

		try 
		{
			if (creado == 0){
				logdt.logData_Info("creado = 0");
		        
				contador = 0;
				logdt.logData_Info("numero conexiones: "+numConn);
				as400Pool = new AS400ConnectionPool ();
				as400Pool.setMaxConnections(numConn+1);//Maximo Numero de conexiones
				as400Pool.setMaxLifetime(1000*60*2);//tirempo maxiomo de vida 30min
				as400Pool.fill(host, user, password, AS400.DATAQUEUE, numConn);//crea n conexiones
				
						
				//as400 = new AS400(host, user, password);
	        	pathIn = new QSYSObjectPathName(libDTQ, nameDTQ, "DTAQ");
				
				creado = 1;
				logdt.logData_Debug("Se iniciaron las variables de conexion");
				
			}
			
			logdt.logData_Debug("Number of active connections: " +
			as400Pool.getActiveConnectionCount(host, user));
			logdt.logData_Debug("Number of available connections for use: " +
			as400Pool.getAvailableConnectionCount(host, user));
							
			as400 = as400Pool.getConnection(host, user, password,AS400.DATAQUEUE);
					
			logdt.logData_Debug("Number of active connections: " +
			as400Pool.getActiveConnectionCount(host, user));
			logdt.logData_Debug("Number of available connections for use: " +
			as400Pool.getAvailableConnectionCount(host, user));
					
			kdqIn = new DataQueue(as400, pathIn.getPath());		
					
			logdt.logData_Debug("AS400:"+as400.toString());

			
			MbMessage inMessage = assembly.getMessage();
			MbElement outRoot = inMessage.getRootElement().getLastChild().getLastChild();
			contador = contador +1;
			logdt.logData_Info("contador:"+contador);
	        
			kdqIn.write((byte[])outRoot.getValue());
			logdt.logData_Info("Mensaje:"+(byte[])outRoot.getValue());
			
			sendOuput(assembly);
			
			as400Pool.returnConnectionToPool(as400);
	        
		} catch (MbBrokerException mbbe) {
			if (creado == 1)
				as400Pool.returnConnectionToPool(as400);
			logdt.logData_Error("Error Metodo evaluate MbBrokerException:: ", mbbe);
			mbbe.printStackTrace();
			throw mbbe;
		}catch (MbException e) {
			if (creado == 1)
				as400Pool.returnConnectionToPool(as400);
			logdt.logData_Error("Error Metodo evaluate MbBrokerException:: ", e);
			e.printStackTrace();
			throw e;
		}
		catch (Exception e) {
			
			if (creado == 1)
				as400Pool.returnConnectionToPool(as400);
			logdt.logData_Error("Error Metodo evaluate :: ",e);
			e.printStackTrace();
			throw new MbUserException("com.ibm.broker.as400plugin", "evaluate","WMQI","1010","Exception as400o node", new String [] {e.toString()});
			
		}

	}
	// ---------------------------------			
	// The AS400O server command processor
private void sendOuput(MbMessageAssembly assembly) throws Exception {
		
		logdt.logData_Debug("Entra Metodo sendOutput");
		
		MbOutputTerminal terminal1 = getOutputTerminal("out");
			
		terminal1.propagate(assembly);
			
	}
	
	public void onDelete() {
		//logdt.logData_Info("DESCONECTAR ANTES");	
		
		if (creado == 1)
			as400Pool.close();
		
		logdt.logData_Debug("Eliminando Conexiones");
		creado = 0;
		}
	
	
	public String getHost() {
		
		return (this.host);
	}
	
	public void setHost(String host) {
		
		this.host=host;
	}
	
	public String getUser() {
		
		return (this.user);
	}
	
	public void setUser(String user) {
		
		this.user=user;
	}
	public String getPassword() {
		
		return (this.password);
	}
	
	public void setPassword(String password) {
		
		this.password=password;
	}
	
	public String getLibDTQ() {
		
		return (this.libDTQ);
	}
	
	public void setLibDTQ(String libDTQ) {
		
		this.libDTQ=libDTQ;
	}
	
	public String getNameDTQ() {
		
		return (this.nameDTQ);
	}
	
	public void setNameDTQ(String nameDTQ) {
		
		this.nameDTQ=nameDTQ;
	}
	
	public String getNumeroConexiones() {
		
		return (String.valueOf(this.numConn));
	}
	
	public void setNumeroConexiones(String nameDTQ) {
		
		
		this.numConn =Integer.parseInt(nameDTQ) ;
	}
	

/*for node properties attribute 'logLevel'*/
	public String getLogLevel()
	{
		String level = null;
		
		switch (logLevel)
		{
			case LogTraceData.LOGDATA_LEVEL_NONE: 
										level = "NONE";
										break;
			case LogTraceData.LOGDATA_LEVEL_DEBUG:
										level = "DEBUG";
										break;
			case LogTraceData.LOGDATA_LEVEL_INFO:
			 							level = "INFO";
										break;
			case LogTraceData.LOGDATA_LEVEL_ERROR:
										level = "ERROR";
										break;
		}		
		return level;	
	}
	/*for node properties attribute 'logLevel' used by broker*/
	public void setLogLevel(String level)
	{
		if(level == null) return;
		
		if(level.equals("NONE"))
			logLevel = LogTraceData.LOGDATA_LEVEL_NONE;
		else if(level.equals("DEBUG")) 
			logLevel = LogTraceData.LOGDATA_LEVEL_DEBUG;
		else if(level.equals("INFO")) 
			logLevel = LogTraceData.LOGDATA_LEVEL_INFO;
		else if(level.equals("ERROR"))
			logLevel = LogTraceData.LOGDATA_LEVEL_ERROR;
	}
	/*
	 * This function need to be called only once as part of initializing the node...
	 * */	


	
}